package com.exercise.AndroidCamera;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.SocketTimeoutException;
import java.net.URL;
import java.util.ArrayList;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.exercise.AndroidCamera.CreateGroupActivity.friendListAsync;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Typeface;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
/*
기능 : 그룹생성
작성 : 하드캔
완료일 : 2014.09.26 
	*/
public class CreateGroupActivity extends BaseActivity implements OnItemClickListener {

	Intent mIntent;
	String userID;
	String group_name = "";
	String group_detail = "";
	
	EditText editGroupName;
	EditText editGroupEp;
	
	LinearLayout linLayout;
	
	private ListView list;
	ArrayList<String> friendArray;
	ArrayList <String> checkedValue;
	
	Button addFriend;
	JSONObject obj;
	JSONArray arr;
	
	boolean[] itemChecked;
	
	CheckBox check;
	
	LinearLayout checkgrouplayout;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_create_group);
		
		friendArray = new ArrayList<String>();
		
		userID = getIntent().getExtras().getString("userID");
		linLayout = (LinearLayout) findViewById(R.id.container);
		
		getActionBar().setTitle("Post Memories");
		getActionBar().setDisplayShowHomeEnabled(false);
		getActionBar().setDisplayHomeAsUpEnabled(true);

		editGroupName = (EditText)findViewById(R.id.editGroupName);
		editGroupEp = (EditText)findViewById(R.id.editGroupEp);
		addFriend = (Button)findViewById(R.id.btnAddFriend);
		checkgrouplayout = (LinearLayout)findViewById(R.id.checkgrouplayout);
		
		
		obj = new JSONObject();
		arr = new JSONArray();

		friendListAsync friendList = new friendListAsync();
		friendList.execute();

	}
	
	//comment 
	protected String[] friend_list_read(Context context, String location_id){
		String pString = null;
		HttpURLConnection conn = null;
		BufferedReader br = null;
		
		String[] result = new String[2];
		result[0] = "error"; //JSON flag
		result[1] = null; //message
		
		try{
       	StringBuilder builder = new StringBuilder();
       	
       	URL url = new URL("http://54.199.194.197/list_friend.php");
       	conn = (HttpURLConnection)url.openConnection();
       	
       	if(conn != null){
       		conn.setConnectTimeout(150000);	
       		conn.setReadTimeout(150000);
       		conn.setDefaultUseCaches(false); 
           	conn.setDoInput(true); 
           	conn.setDoOutput(true);  
           	conn.setRequestMethod("POST"); 
           	conn.setRequestProperty("content-type", "application/x-www-form-urlencoded"); 
              
         	StringBuffer buffer = new StringBuffer();
         	buffer.append("user_id").append("=").append(userID);
         	Log.d("user_id_comment", buffer.toString());

            OutputStreamWriter outStream = new OutputStreamWriter(conn.getOutputStream(), "UTF-8");
            PrintWriter writer = new PrintWriter(outStream);
            writer.write(buffer.toString());
            writer.flush();
            
            InputStreamReader inputStream = new InputStreamReader(conn.getInputStream(), "UTF-8"); 
            br = new BufferedReader(inputStream);
              
           	String line;
           	while((line = br.readLine()) != null){
           	   builder.append(line);
           	}
              
           	br.close();
           	
           	pString =  builder.toString();
           	Log.d("pString in read comment", pString);
           	
           	JSONObject jObject = new JSONObject(pString);
           	JSONArray friendObject = new JSONArray(jObject.getString("friend_id"));
           	
           	for(int i=0; i<friendObject.length(); i++){
           		friendArray.add(friendObject.getString(i));
           	}
           	
       	}else{
       		
       		throw new Exception("network error");
       	}
       	
       }catch(SocketTimeoutException se){
       	
       	result[1] = "network error";
       	
       }catch(Exception e){
       	
       	result[1] = e.getMessage();
       	
       }finally{
       	
       	if(conn != null)
       		conn.disconnect();

       	if(br != null){
       		try {
       			br.close();
				} catch (Exception e2) {
					// TODO: handle exception
					result[1] = e2.getMessage();
				}
       	}
       }
       return result;
	}
	
	public class friendListAsync extends AsyncTask<String, String, String> {
		@Override
		protected void onPreExecute() {
			super.onPreExecute();
		}
		@Override
		protected String doInBackground(String... params) {
			friend_list_read(CreateGroupActivity.this, "0");
			return null;
		}
		@Override
		protected void onPostExecute(String result) {
			Typeface tf = Typeface.createFromAsset(CreateGroupActivity.this.getAssets(), "fonts/whitechok.ttf");

			Log.d("friendArray.size()",friendArray.size()+"");
			for(int i=0; i<friendArray.size(); i++){
				    check = new CheckBox(CreateGroupActivity.this);
				    check.setLayoutParams (new LayoutParams (LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
				    check.setText(friendArray.get(i));
				    check.setId(i);
				    check.setTypeface(tf);
				    check.setGravity(Gravity.CENTER);
				    check.setTextColor(0xFFFF6E57);
				    checkgrouplayout.addView(check);
			}

			

			addFriend.setOnClickListener(new View.OnClickListener() {
				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
					
					  group_name = editGroupName.getText().toString();
					  group_detail = editGroupEp.getText().toString(); 
					  
					  
				      for(int n=0; n<friendArray.size(); n++)
				      {				      
					      CheckBox friendCheckBox = new CheckBox(CreateGroupActivity.this);
					      friendCheckBox = (CheckBox) checkgrouplayout.findViewById(n);
					      
					      if(friendCheckBox.isChecked())
					      {
					    	  try {
								obj.put("friend_id", arr.put((String)friendCheckBox.getText()));						    	
							} catch (JSONException e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							}
					    	  Log.d("friend_id", (String)friendCheckBox.getText());
					      }
				      }
				      
				    createGroupAsync addgroup = new createGroupAsync();
					addgroup.execute();
				}
			});
			 
			super.onPostExecute(result);
		}
		@Override
		protected void onCancelled() {
			super.onCancelled();
		}
	}
	
	//comment
	protected String[] create_group_info(Context context, String location_id){
		String pString = null;
		HttpURLConnection conn = null;
		BufferedReader br = null;
		
		String[] result = new String[2];
		result[0] = "error"; //JSON flag
		result[1] = null; //message
		
		try{
       	StringBuilder builder = new StringBuilder();
       	
       	URL url = new URL("http://54.199.194.197/create_group.php");
       	conn = (HttpURLConnection)url.openConnection();
       	
       	if(conn != null){
       		conn.setConnectTimeout(1500000000);	
       		conn.setReadTimeout(1500000000);
       		conn.setDefaultUseCaches(false); 
           	conn.setDoInput(true); 
           	conn.setDoOutput(true);
           	conn.setRequestMethod("POST");
           	conn.setRequestProperty("content-type", "application/x-www-form-urlencoded");
              
         	StringBuffer buffer = new StringBuffer();
         	buffer.append("user_id").append("=").append(userID).append("&");
         	buffer.append("friend_id").append("=").append(obj).append("&");
         	buffer.append("group_name").append("=").append(group_name).append("&");
         	buffer.append("group_detail").append("=").append(group_detail);

         	Log.d("friend_id", obj+"");

            
            OutputStreamWriter outStream = new OutputStreamWriter(conn.getOutputStream(), "UTF-8");
            PrintWriter writer = new PrintWriter(outStream);
            writer.write(buffer.toString());
            writer.flush();
            
            
            InputStreamReader inputStream = new InputStreamReader(conn.getInputStream(), "UTF-8"); 
            br = new BufferedReader(inputStream);
              
           	String line;
           	while((line = br.readLine()) != null){
           	   builder.append(line);
           	}
              
           	br.close();
           	
           	pString =  builder.toString();
           	Log.d("pString", pString);
           	
           	JSONObject jObject = new JSONObject(pString);
           	
       	}else{
       		
       		throw new Exception("network error");
       	}
       	
       }catch(SocketTimeoutException se){
       	
       	result[1] = "network error";
       	
       }catch(Exception e){
       	
       	result[1] = e.getMessage();
       	
       }finally{
       	
       	if(conn != null)
       		conn.disconnect();

       	if(br != null){
       		try {
       			br.close();
				} catch (Exception e2) {
					// TODO: handle exception
					result[1] = e2.getMessage();
				}
       	}
       }
       return result;
	}
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch(item.getItemId()){
			    
			    case android.R.id.home:
		            onBackPressed();
		            break;
		
			    default:
			        return false;
			    }
			    return true;
	}
	
	public class createGroupAsync extends AsyncTask<String, String, String> {
		@Override
		protected void onPreExecute() {
			super.onPreExecute();
		}
		@Override
		protected String doInBackground(String... params) {
			create_group_info(CreateGroupActivity.this, "0");
			return null;
		}
		@Override
		protected void onPostExecute(String result) {
			// toast
			Toast.makeText(getApplicationContext(), "그룹생성.", Toast.LENGTH_SHORT).show();
			mIntent = new Intent(CreateGroupActivity.this, ManageGroupActivity.class);
	        mIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
	        mIntent.putExtra("userID", userID);
    		startActivity(mIntent);
			super.onPostExecute(result);
		}
		@Override
		protected void onCancelled() {
			super.onCancelled();
		}
	}

	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position,
			long id) {
		// TODO Auto-generated method stub
		
	}

}
